package com.zansc.longd.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;

import java.util.Date;

public class JWTUtils {
    
    /**
     * 过期时间12个小时
     */
    private static final long TIME = 1000 * 60 * 60 * 12;
    
    public static String sign(String username, String tg) {
        try {
            Date date = new Date(System.currentTimeMillis() + TIME);
            Algorithm algorithm = Algorithm.HMAC256(tg);
            return JWT.create()
                    .withClaim("username", username)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (IllegalArgumentException e) {
            return null;
        } catch (JWTCreationException e) {
            return null;
        }
    }
    
    public static String getUsername(String token) {
        try {
            return JWT.decode(token).getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }
    
    public static boolean isExpires(String token) {
        return System.currentTimeMillis() > JWT.decode(token).getExpiresAt().getTime();
    }
    
    public static boolean verify(String token,String username,String secret) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("username", username)
                    .build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    
}
